from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from sirogi.documents.models import Document
from sirogi.users.models import SirogiUser
from sirogi.states.models import State
from django.contrib.auth.decorators import user_passes_test
from convert import Convert
from django.template import RequestContext
import os
import shutil


@user_passes_test(lambda u: u.has_perm('documents.change_document'), login_url='/login/')
def index(request):
    try:
        #import pdb; pdb.set_trace()
        if not (hasattr(request.user,'role') and ((request.user.role == u'I') or (request.user.role == u'M'))):
            return HttpResponseRedirect('/login/')

        #creo la lista de los usuarios que son redactores 
        users = list(SirogiUser.objects.filter(role = 'E'))

        documents = ret_document(request)

        return render_to_response('approve/approve_list.html', {'results_user': users, 'documents': documents}, RequestContext(request))
    except:
        return render_to_response('approve/approve_list.html', {'message': 'Error in the transaction'}, RequestContext(request))

@user_passes_test(lambda u: u.has_perm('documents.change_document'), login_url='/login/')
def status_approve(request, id_doc):
    try:
        if not (hasattr(request.user,'role') and ((request.user.role == u'I') or (request.user.role == u'M'))):
            return HttpResponseRedirect('/login/')
        #Cambio el estado del documento dependiendo de que se pueda hacer
        users = SirogiUser.objects.filter(role = 'E')
        doc = get_object_or_404(Document, id=id_doc)
            

        #TODO CAMBIAR ESTADO Y
        #TODO CONVERTIR EL DOCUMENTO
        
        #import pdb; pdb.set_trace()
        con = Convert()
        os.chdir(os.path.join(request.META['PWD'],'latex'))
        con.save_latex(doc.numDoc, doc.visto, doc.considerando, doc.resuelve)
        os.system('pdflatex ' + str(doc.numDoc) + '.tex')
        
        if (str(doc.numDoc) + '.pdf') in os.listdir('.'):
            shutil.copy((str(doc.numDoc) + '.pdf'), ('../final_documents/' + (str(doc.numDoc) + '.pdf')))
            doc.state = get_object_or_404(State, Name='A')
            doc.save()
            
        #os.system('pdflatex latex/' + str(doc.id) + '.tex')
        documents = ret_document(request)
        return render_to_response('approve/approve_list.html', {'results_user': users, 'message': 'The document was approved', 'documents': documents}, RequestContext(request))
    except:
        return render_to_response('approve/approve_list.html', {'message': 'Error in the transaction. The document does not exist.'}, RequestContext(request))

@user_passes_test(lambda u: u.has_perm('documents.change_document'), login_url='/login/')
def status_disapprove(request, id_doc):
    try:
        if not (hasattr(request.user,'role') and ((request.user.role == u'I') or (request.user.role == u'M'))):
            return HttpResponseRedirect('/login/')

        #Cambio el estado del documento dependiendo de que se pueda hacer
        users = SirogiUser.objects.filter(role = 'E')
        doc = get_object_or_404(Document, id=id_doc)

        doc.state = get_object_or_404(State, Name='C')
        doc.save()

        documents = ret_document(request)
        return render_to_response('approve/approve_list.html', {'results_user': users, 'message': 'The document was disapproved', 'documents': documents}, RequestContext(request))
    except:
        return render_to_response('approve/approve_list.html', {'message': 'Error in the transaction. The document does not exist.'}, RequestContext(request))

@user_passes_test(lambda u: u.has_perm('documents.change_document'), login_url='/login/')
def status_edit(request, id_doc):
    try:
        if not (hasattr(request.user,'role') and ((request.user.role == u'I') or (request.user.role == u'M'))):
            return HttpResponseRedirect('/login/')

        #Cambio el estado del documento dependiendo de que se pueda hacer
        users = SirogiUser.objects.filter(role = 'E')
        doc = get_object_or_404(Document, id=id_doc)
        
        doc.state = get_object_or_404(State, Name='M')
        doc.save()

        #TODO CAMBIAR ESTADO
        documents = ret_document(request)
        return render_to_response('approve/approve_list.html', {'results_user': users, 'message': 'The document was marked', 'documents': documents}, RequestContext(request))
    except: 
        return render_to_response('approve/approve_list.html', {'message': 'Error in the transaction. The document does not exist.'}, RequestContext(request))

def ret_document(request):
    #busco los documentos segun los parametros pasados
        if request.POST.has_key('user'):
            if request.POST['user'] != "-1":
                user = get_object_or_404(SirogiUser, NIC=request.POST['user'])
                documents = Document.objects.filter(owner = user)	
            else:
                documents = Document.objects.all()
        else:
            documents = Document.objects.all()
                
        if request.POST.has_key('document_nro'):
            try:
                value = int(request.POST['document_nro'])
                documents = documents.filter(numDoc = value)
            except ValueError:
                pass		
        
        documents = documents.filter(state__Name = 'E')
        
        return documents
    
